//
//  SWPagePhotoView.swift
//  YiyaPuzzleDemo
//
//  Created by linhan on 16/10/9.
//  Copyright © 2016年 test. All rights reserved.
//

import Foundation
import UIKit

@objc protocol SWPagePhotoViewDelegate:NSObjectProtocol
{
    func pagePhotoViewSingleTap(_ photoView:SWPagePhotoView)
    //optional func pagePhotoViewContentChanged(photoView:SWPagePhotoView)
    @objc optional func pagePhotoViewSwap(_ photoView:SWPagePhotoView)
    @objc optional func pagePhotoViewLongPress(_ photoView:SWPagePhotoView)
    @objc optional func pagePhotoViewDelete(_ photoView:SWPagePhotoView)
}

typealias SWPagePhotoViewRect = (view:SWPagePhotoView,rect:CGRect)


extension SWDragManager
{
    //photoView区域
    var photoViewRects:[SWPagePhotoViewRect]{
        if let viewControllers = pageViewController?.viewControllers as? [SWPageViewController]
        {
            var rects:[SWPagePhotoViewRect] = []
            for vc in viewControllers
            {
                rects += vc.photoViewRects
            }
            return rects
        }
        return []
    }
}

class SWPagePhotoView: UIView
{
    var photo:SWPhoto
    var previewMode:Bool = false
    weak var delegate:SWPagePhotoViewDelegate?
    
    var image:UIImage?
    {
        get{
            return _imageView.image
        }
        set{
            _imageView.image = newValue
        }
    }
    
    //要求的图片最小尺寸，当图片小于此尺寸时进行警示
    private var _limitSize:CGSize = CGSizeZero
    private var _imageView:UIImageView = UIImageView()
    private var _deleteBtn:UIButton = UIButton(type: .custom)
    private var _warningIcon:UIImageView = UIImageView(image: UIImage(named:"global_icon_warning"))
    
    override var frame: CGRect
    {
        get
        {
            return super.frame
        }
        set
        {
            super.frame = newValue
            frameChanged(newValue)
        }
    }
    
    //处于待删除状态
    var deletable:Bool = false{
        didSet{
            let showDeleteButton = {
                if self._deleteBtn.isHidden
                {
                    self._deleteBtn.isHidden = false
                    self._deleteBtn.alpha = 0
                    self._deleteBtn.transform = CGAffineTransform(scaleX: 0.1, y: 0.1)
                    UIView.animate(withDuration: 0.2, animations: {
                        self._deleteBtn.alpha = 1
                        self._deleteBtn.transform = CGAffineTransform.identity
                    })
                }
            }
            
            let hideDeleteButton = {
                if !self._deleteBtn.isHidden
                {
                    UIView.animate(withDuration: 0.2, animations: {
                        self._deleteBtn.alpha = 0
                        self._deleteBtn.transform = CGAffineTransform(scaleX: 0.1, y: 0.1)
                        },completion: { finish in
                            self._deleteBtn.isHidden = true
                    })
                }
            }
            
            if deletable
            {
                if let imageID = photo.imageID, imageID != ""{
                    showDeleteButton()
                }
                else
                {
                    hideDeleteButton()
                }
            }
            else
            {
                hideDeleteButton()
            }//end else(hidden)
        }//end didSet
    }
    
    init(photo:SWPhoto)
    {
        self.photo = photo
        super.init(frame: CGRectZero)
        let size = SW.Config.BookSinglePageSize
        _limitSize = CGSizeMake(size.width * CGFloat(photo.widthPercent ?? 0), size.height * CGFloat(photo.heightPercent ?? 0))
        //trace("_limitSize:", _limitSize)
        setup()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit
    {
        NotificationCenter.default.removeObserver(self)
        print("DEINIT SWPagePhotoView")
    }
    
    private func setup()
    {
        backgroundColor = UIColor(white: 0.9, alpha: 1)
        
        let tagGesture:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(viewTapped))
        addGestureRecognizer(tagGesture)
        
        let longPressGesture:UILongPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(viewLongPressed(_:)))
        addGestureRecognizer(longPressGesture)
        
        _imageView.contentMode = .scaleAspectFill
        _imageView.clipsToBounds = true
        addSubview(_imageView)
        
        _deleteBtn.setImage(UIImage(named:"global_btn_close"), for: .normal)
        _deleteBtn.sizeToFit()
        _deleteBtn.isHidden = true
        _deleteBtn.addTarget(self, action: #selector(deleteBtnTapped), for: .touchUpInside)
        addSubview(_deleteBtn)
        
        _warningIcon.center = CGPointMake(20, 20)
        _warningIcon.isHidden = true
        addSubview(_warningIcon)
        
        imageViewUpdate()
        
        //NSNotificationCenter.default.addObserver(self, selector: #selector(photoUpdatedNotification(_:)), name: NotificationName.PhotoUpdated, object: nil)
    }
    
    func swapContent(_ start:Bool = false)
    {
        imageViewUpdate(false)
        //照片拖入空格时，原来位置的删除按钮隐藏，新位置的删除按钮显示
        deleteButtonUpdate()
        delegate?.pagePhotoViewSwap?(self)
    }
    
    func imageViewUpdate(_ animated:Bool = false)
    {
        let imageEmpty = {
            self._imageView.image = nil
            self._warningIcon.isHidden = true
            self.deletable = false
        }
        
        if let imageID = photo.imageID, imageID != ""
        {
            
            SWBookAssetManager.sharedManager().ioQueue.async
            {
                let image = SWBookAssetManager.sharedManager().getImage(imageID, level: .preview, scale: 0)
                DispatchQueue.main.async(execute: {
                    
                    if let image = image
                    {
                        let size = image.originSize
                        let lowPixel = size.width < self._limitSize.width || size.height < self._limitSize.height
                        //trace("lowPixel:", lowPixel, size, self._limitSize)
                        //self._warningIcon.hidden = !lowPixel
                        if animated
                        {
                            UIView.transition(with: self._imageView, duration: 0.3, options: .transitionCrossDissolve, animations: {
                                self._imageView.image = image
                            } , completion: nil)
                        }
                        else
                        {
                            self._imageView.image = image
                        }
                        
                        if !self.previewMode
                        {
                            self.deletable = true
                        }
                    }
                    else
                    {
                        imageEmpty()
                    }
                    
                })
            }
        }
        else
        {
            imageEmpty()
        }
        
    }
    
    private func deleteButtonUpdate()
    {
        deletable = SWDragManager.sharedManager().deleting
    }
    
    private func frameChanged(_ rect:CGRect)
    {
        let newBounds = CGRect(origin: CGPointZero, size: rect.size)
        _imageView.frame = newBounds
        _deleteBtn.frame = CGRectMake(newBounds.width - _deleteBtn.width - 5, 5, _deleteBtn.width, _deleteBtn.height)
    }
    
    @objc private func viewTapped()
    {
        delegate?.pagePhotoViewSingleTap(self)
    }
    
    @objc private func viewLongPressed(_ recognizer:UILongPressGestureRecognizer)
    {
        if recognizer.state == UIGestureRecognizerState.began
        {
            delegate?.pagePhotoViewLongPress?(self)
        }
    }
    
    @objc private func photoUpdatedNotification(notification:NSNotification)
    {
        if let nid = notification.userInfo?["imageID"] as? String,
            let iid = photo.imageID, nid != "" && nid == iid
        {
            setTimeout(0.2, closure: {[weak self] in
                self?.imageViewUpdate(true)
            })
        }
    }
    
    @objc private func deleteBtnTapped()
    {
        delegate?.pagePhotoViewDelete?(self)
    }
    
    
}
